/**
 * Copyright (c) 2007, Blue Hole Software. All rights reserved.
 * Code licensed under the Apache 2.0 License:
 * http://www.apache.org/licenses/
 */

package org.bhf.service.view;

import org.bhf.service.ProcessView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Simply set the status code and return. Useful for errors that you want the browser to render. If used as the view
 * of a Service method, the method MUST return an integer.
 */
public class StatusProcessView implements ProcessView
{
    private final int status;

    /**
     * Render the view as a JSON exception with the given status code.
     *
     * @param status HTTP status code
     */
    public StatusProcessView( final int status )
    {
        this.status = status;
    }

    /**
     * Render the view as a JSON exception with the given status code.
     *
     * @param service Not used
     * @param method The target service method
     * @param result Result of the method invocation. Must be an Integer
     */
    public StatusProcessView( final Object service, final Method method, final Object result )
    {
        if( !(result instanceof Integer) )
            throw new IllegalArgumentException();

        this.status = (Integer)result;
    }

    /**
     *
     * @param request Servlet request
     * @param response Servlet response
     * @param servletContext The servlet context for this application
     * @throws IOException ConversionError writing body
     * @exclude
     */
    public void processView( final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext )
        throws IOException
    {
        response.setStatus( status );
    }
}